const wxRequest = function(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      success: function(res) {
        resolve(res);
      }
    });
  });
};

module.exports = function(Mogo) {
  const State = Mogo.State;
  Mogo.request = async function(data) {
    const userState = State.get("mogoUser");
    let token = "";
    if (userState && userState.token) {
      token = userState.token;
    }
    // 连接上 baseUrl
    const reg = /^https?:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
    if (!reg.test(data.url)) {
      data.url = Mogo._config.domain + data.url;
    }
    try {
      const conf = {
        headers: {
          Authorization: token
        },
        baseURL: Mogo._config.domain,
        ...data
      };
      const res = await wxRequest(conf);
      return res.data;
    } catch (error) {
      // 触发报错器
      Mogo._config.ajaxErrorHandel && Mogo._config.ajaxErrorHandel(error);
      return await Promise.reject(error.response);
    }
  };
};
